<template>
  <div class="component-brand-add-or-update">
    <el-dialog
      v-model="visible"
      :title="!dataForm.brandId ? $t('brand.add') : $t('brand.revise')"
      :close-on-click-modal="false"
      width="570px"
      @close="closeDialogHandle"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="auto"
      >
        <!-- 语言选择 -->
        <el-form-item
          v-if="langItemList.length > 1"
          :label="$t('product.selectLanguage')"
        >
          <el-select
            v-model="curLang"
            multiple
            :placeholder="$t('tip.select')"
            style="width: 100%;"
            @change="selectLang"
          >
            <el-option
              v-for="item in langItemList"
              :key="item.lang"
              :label="item.name"
              :value="item.lang"
            />
          </el-select>
        </el-form-item>
        <!-- 品牌名称 -->
        <template v-if="dataForm.type !== 2">
          <div
            v-for="(item, index) in brandLangList"
            :key="index"
          >
            <el-form-item
              :prop="'lang_' + item.lang"
              :label="$t('brand.brandName') + (langItemList.length === 1 ? '' : `(${item.langName})`)"
            >
              <el-input
                v-model.trim="dataForm['lang_' + item.lang]"
                maxlength="20"
                show-word-limit
                @change="(v) => item.name = v"
              />
            </el-form-item>
          </div>
        </template>

        <!-- 品牌首字母 -->
        <el-form-item
          :label="$t('brandPopups.brandInitials')"
          prop="firstLetter"
        >
          <el-input
            v-model="dataForm.firstLetter"
            type="text"
            :placeholder="$t('brandPopups.inputBrandInitials')"
            maxlength="1"
            show-word-limit
          />
        </el-form-item>
        <!-- 品牌logo -->
        <el-form-item
          :label="$t('brandPopups.brandLogo')"
          prop="imgUrl"
        >
          <img-upload v-model="dataForm.imgUrl" />
        </el-form-item>
        <!-- 平台分类 -->
        <el-form-item
          :label="$t('product.platformClassification')"
          prop="categoryIds"
        >
          <el-select
            v-model="dataForm.categoryIds"
            multiple
            class="select-categoryId"
            :placeholder="$t('tip.select') + $t('product.platformClassification')"
          >
            <el-option
              v-for="(item, index) in categoryList"
              :key="index"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <!-- 序号 -->
        <el-form-item
          :label="$t('brand.sequence')"
          prop="seq"
        >
          <el-input
            v-model="dataForm.seq"
            type="number"
            :max="32767"
            :min="0"
            @blur="handleSortValue"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >{{ $t("remindPop.cancel") }}</div>
          <div
            class="default-btn primary-btn"
            @click="dataFormSubmit()"
          >{{ $t("remindPop.confirm") }}</div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits('refreshDataList')

const validateFirstLetter = (rule, value, callback) => {
  const regexp = /^[A-Z]{1}$/
  if (!regexp.test(value)) {
    callback(new Error('请输入一位大写字母'))
  } else {
    callback()
  }
}

const validateCategory = (role, value, callback) => {
  if (value.length === 0) {
    callback(new Error($t('user.selectCategory')))
  } else {
    callback()
  }
}

const Data = reactive({
  dataForm: {
    brandId: 0,
    imgUrl: '',
    brief: '',
    seq: 0,
    status: 1,
    firstLetter: '',
    categoryIds: []
  },
  brandSelectVisible: false,
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  selectedCategories: [],
  // 分类list
  categoryList: [],
  categorySelectorVisible: false, // 分类弹窗显隐
  dataRule: {
    lang_0: [
      { required: true, message: $t('brandPopups.emptyBrandName'), trigger: 'blur' }
    ],
    lang_1: [
      { required: true, message: $t('brandPopups.emptyBrandName'), trigger: 'blur' }
    ],
    firstLetter: [
      { required: true, message: $t('brandPopups.emptyBrandInitials'), trigger: 'blur' },
      { validator: validateFirstLetter, trigger: 'blur' }
    ],
    seq: [
      { required: true, message: $t('brandPopups.emptysequence'), trigger: 'blur' }
    ],
    imgUrl: [
      { required: true, message: $t('brandPopups.selectLogo'), trigger: 'blur' }
    ],
    categoryIds: [
      { required: true, message: $t('user.selectCategory'), trigger: 'change', validator: validateCategory }
    ]
  },
  visible: false,
  // 语言列表
  langItemList: [],
  masterLangInfo: { name: '', lang: '' },
  // 当前所选语言
  curLang: [],
  brandLangList: []
})

const { dataForm, categoryList, dataRule, visible, langItemList, curLang, brandLangList } = toRefs(Data)

const dataFormRef = ref()
// 获取分类数据
const init = (id) => {
  Data.selectedCategories = []
  Data.visible = true
  Data.dataForm.brandId = id || 0
  nextTick(() => {
    dataFormRef.value.resetFields()
  })
  if (Data.dataForm.brandId) {
    // 获取产品数据
    http({
      url: http.adornUrl(`/platform/brand/info/${Data.dataForm.brandId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      Data.dataForm = data
      Data.dataForm.categoryIds = data.categories ? data.categories.map(x => x.categoryId) : []
      data.brandLangList.forEach(d => {
        Data.dataForm['lang_' + d.lang] = d.name
      })
      // Data.categoryShow(data.categories) // 分类回显
      // 国际化处理
      Data.brandLangList = data.brandLangList
      getLangList()
      // 获取平台分类
      getCategoryList()
    })
  } else {
    // 获取平台分类
    getCategoryList()
    nextTick(() => {
      dataFormRef.value.resetFields()
      Data.dataForm.brandPic = ''
      Data.relation = null
    })
    getLangList()
    Data.brandLangList = []
  }
}

const getLangList = () => {
  http({
    url: http.adornUrl('/sys/lang'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      const info = data
      Data.masterLangInfo.name = info.name
      Data.masterLangInfo.lang = info.lang
      Data.langItemList = info.langItemList
      if (Data.dataForm.brandId) {
        const curLang = []
        const brandLangList = []
        for (const item of Data.langItemList) {
          const fd = Data.brandLangList.find(it => it.lang === item.lang)
          if (fd) {
            fd.language = item.language
            fd.langName = item.name
            brandLangList.push(fd)
            curLang.push(item.lang)
          }
        }
        Data.brandLangList = brandLangList
        selectLang(curLang)
      } else {
        // 设置默认主语言
        selectLang([info.lang])
      }
    }
  })
}

// 多选框默认选择主语言
const selectLang = (value) => {
  Data.curLang = value
  // 设置主语言不可删除
  if (!Data.curLang.includes(Data.masterLangInfo.lang)) {
    Data.curLang.unshift(Data.masterLangInfo.lang)
  }
  // 分类名称
  const tempArr = Data.brandLangList.filter(item => Data.curLang.includes(item.lang))
  Data.curLang.forEach((item, index) => {
    if (!tempArr.find(f => f.lang == item)) {
      const fd = Data.langItemList.find(it => it.lang === item)
      if (fd) {
        tempArr.splice(index, 0, { language: fd.language, langName: fd.name, lang: item, brandId: Data.dataForm.brandId, name: '' })
      }
    }
  })
  Data.brandLangList = tempArr
}

// 获取平台分类列表
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategoryByGrade'),
    method: 'get',
    params: http.adornParams({
      grade: 0,
      status: 1
    })
  }).then(({ data }) => {
    Data.categoryList = data
  })
}

// 处理排序输入框
const handleSortValue = () => {
  if (Data.dataForm.seq > 32767) {
    Data.dataForm.seq = 32767
    return
  }
  if (Data.dataForm.seq <= 0 || !Data.dataForm.seq) {
    Data.dataForm.seq = 0
  }
}

// 表单提交
const dataFormSubmit = Debounce(() => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      const param = Data.dataForm
      for (const item of Data.brandLangList) {
        if (!item.name) {
          ElMessage({
            message: $t('brandPopups.emptyBrandName'),
            type: 'error',
            duration: 1500
          })
          return
        }
      }
      param.brandLangList = Data.brandLangList
      http({
        url: http.adornUrl('/platform/brand'),
        method: param.brandId ? 'put' : 'post',
        data: http.adornData(param)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            Data.visible = false
            emit('refreshDataList', Data.page)
          }
        })
      })
    }
  })
}, 1500)

// 关闭对话框回调
const closeDialogHandle = () => {
  dataFormRef.value.resetFields()
  Data.dataForm.relation = null
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.component-brand-add-or-update {
  .select-categoryId {
    width: 60%;
  }
}
</style>
